// wx.request封装
const app = getApp()

const request = (url, options) => {
  const token = wx.getStorageSync('token');
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.host}${url}`,//获取域名接口地址
      method: options.method, //配置method方法
      data: options.data,
      // options.method === 'GET' ? options.data : JSON.stringify(options.data), 
      //如果是GET,GET自动让数据成为query String,其他方法需要让options.data转化为字符串
      header: {
        'content-type': 'application/json', // ; charset=UTF-8
        // 'content-type': 'application/x-www-form-urlencoded',
        'Authorization':token?token:''                
      },
      //header中可以监听到token值的变化
      success: function (res) {
        console.log(url, res.data)
        if (Number(res.statusCode) === 401) {
          wx.navigateTo({
            url: '/pages/app-auth/index',
          })
          reject(res.data)
          return
        }
        if (Number(res.statusCode) !== 200) {
          wx.showToast({title: '通讯错误，稍后再试', image: '/images/icon/icon_error.png',duration:3000})
          reject(res.data)
          return
        }
        if (res.data.code !== 20000) {
          wx.showToast({title: res.data.msg,  image: '/images/icon/icon_error.png',duration:3000})
          reject(res.data)
          return
        }
        resolve(res.data.data)
      },
      fail(error) {
        //返回失败也同样传入reject()方法
        reject(error.data)
      }
    })
  })
}
//封装get方法
const get = (url, options = {}) => {
  return request(url, {
    method: 'GET',
    data: options
  })
}
//封装post方法
const post = (url, options) => {
  return request(url, {
    method: 'POST',
    data: options
  })
}
//封装delete方法
const del = (url, options) => {
  console.log(url,'del')
  return request(url, {
    method: 'DELETE',
  })
}


//抛出wx.request的post,get,put,remove方法
module.exports = {
  get,
  post,
  del
}